//
//  SimpleNetwork.swift
//  SimpleNetwork
//
//  Created by gongtao on 15/3/5.
//  Copyright (c) 2015年 _organizeation. All rights reserved.
//

import Foundation

public enum HttpMethod:String {
    case GET = "GET"
    case POST = "POST"
}

public typealias Completion = ((result: AnyObject?, error:NSError?) -> ())

public class SimpleNetwork {
    
    static let errorDomain = "com.GbProject.error"
    
    //懒加载全局URLSession
    lazy var session:NSURLSession? = {
        return NSURLSession.sharedSession()
    }()
    
    public init() {}
    
    //发送网络请求并解析JSON返回数据
    public func requestJSON(method:HttpMethod, _ URLString:String, _ params:[String: String]?, completion:Completion) {
        if let request = setUpURLRequest(method, URLString, params) {
            session!.dataTaskWithRequest(request, completionHandler: { (data, _, error) -> Void in
                //请求错误,直接回调错误
                if error != nil {
                    completion(result: nil, error: error)
                    return
                }
                //反序列化
                let json:AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: .allZeros, error: nil)
                if json == nil {
                    //反序列化失败
                    let error = NSError(domain: SimpleNetwork.errorDomain, code: -1, userInfo: ["error": "反序列化失败"])
                    completion(result: nil, error: error)
                } else {
                    //反序列化成功
                    dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        completion(result: json, error: nil)
                    })
                }
            }).resume()
        }
    }
    
    //创建链接的URLRequest
    func setUpURLRequest(method:HttpMethod, _ URLString:String, _ params:[String: String]?) -> NSURLRequest? {
        if URLString.isEmpty { return nil }
        //URL = URLString
        var URLQuery = URLString
        var URLRequest:NSMutableURLRequest?
        if method == .GET {
            //GET
            let query = changeParamsToQuery(params)
            if query != nil {
                URLQuery += "?" + query!
            }
            return NSMutableURLRequest(URL: NSURL(string: URLQuery)!)
        } else {
            //POST
            if let query = changeParamsToQuery(params) {
                URLRequest = NSMutableURLRequest(URL: NSURL(string: URLQuery)!)
                URLRequest!.HTTPMethod = method.rawValue
                URLRequest!.HTTPBody = query.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
            }
        }
        return URLRequest
    }
    
    //参数字典转换成字符串
    func changeParamsToQuery(params: [String: String]?) -> String? {
        if params == nil { return nil }
        var array = [String]()
        for (k, v) in params! {
            let str = k + "=" + v.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
            array.append(str)
        }
        return join("&", array)
    }
    
}